package com.dc.viewpager

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayoutMediator
import org.w3c.dom.Text

class ViewPagerActivity : AppCompatActivity() {

    private val fragments = arrayListOf<Fragment>()
    private val titles = arrayOf("本周", "本月", "本年度")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view_pager)

        for (title in titles) {
            fragments.add(ViewPagerFragment.newInstance(title))
        }
        val tabLayout = findViewById<TabLayout>(R.id.tabLayout)
        val viewPager = findViewById<ViewPager2>(R.id.viewPager)
        viewPager.apply {
            adapter = ViewPagerAdapter(this@ViewPagerActivity, fragments)
            // ViewPager2不可滑动
            isUserInputEnabled = false
        }
        TabLayoutMediator(tabLayout, viewPager, true, false) { tab, position ->
//            tab.text = titles[position]

            // 使用自定义tab
            val view = LayoutInflater.from(this).inflate(R.layout.custom_tab_layout, null)
            val tvTab = view.findViewById<TextView>(R.id.tv_tab)
            tvTab.text = titles[position]
            tab.customView = view
        }.attach()

        // 使用自定义tab
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                val tabCount = tabLayout.tabCount

                //遍历选择所有的Tab,如果判断是当前的Tab则进行相关操作，不是则还原操作
                for (i in 0 until tabCount) {
                    val tab = tabLayout.getTabAt(i)
                    //通过tab获取tabView

                    tab?.let {
                        val view = it.customView
                        val tv = view?.findViewById<TextView>(R.id.tv_tab)
                        val iv = view?.findViewById<ImageView>(R.id.iv_tab)
                        if (position == it.position) {
                            tv?.setTextColor(Color.GREEN)
                            iv?.visibility = View.VISIBLE
                        } else {
                            tv?.setTextColor(Color.BLACK)
                            iv?.visibility = View.INVISIBLE
                        }
                    }
                }
            }
        })

    }
}